//
//  JKFileExplorerTextEditViewController.m
//  Baisi
//
//  Created by albert on 2019/2/15.
//  Copyright © 2019 安永博. All rights reserved.
//

#import "JKFileExplorerTextEditViewController.h"
#import "JKFileExplorerItem.h"
#import "JKFileExplorerConst.h"
#import "JKFileExplorerAirDropShareManager.h"
#import "JKFileExplorerPreviewController.h"

@interface JKFileExplorerTextEditViewController ()

/** textView */
@property (nonatomic, weak) UITextView *textView;

/** editButton */
@property (nonatomic, weak) UIButton *editButton;

/** saveButton */
@property (nonatomic, weak) UIButton *saveButton;

/** previewButton */
@property (nonatomic, weak) UIButton *previewButton;

/** shareItem */
@property (nonatomic, strong) UIBarButtonItem *shareItem;

/** encoding */
@property (nonatomic, assign) NSStringEncoding encoding;
@end

@implementation JKFileExplorerTextEditViewController

#pragma mark
#pragma mark - 生命周期

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}

#pragma mark
#pragma mark - 初始化

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = self.navTitle;
    
    [self buildUI];
    
    if (self.isCreateNewFile) {
        
        [self enterEditingMode];
        
        self.encoding = NSUTF8StringEncoding;
        
        return;
    }
    
    [self loadData];
}

- (void)share{
    
    if (!self.filePath) { return; }
    
    NSURL *URL = [NSURL fileURLWithPath:self.filePath];
    
    [JKFileExplorerAirDropShareManager shareWithViewController:self URL:URL];
}

- (void)buildUI{
    
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAction) target:self action:@selector(share)];
    shareItem.enabled = (self.filePath != nil);
    self.navigationItem.rightBarButtonItem = shareItem;
    _shareItem = shareItem;
    
    [self buildTabBar];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, self.isIphoneX ? 88 : 64, self.view.frame.size.width, self.view.frame.size.height - (self.isIphoneX ? 88 : 64) - self.tabBar.frame.size.height)];
    textView.font = [UIFont systemFontOfSize:15];
    textView.editable = self.isCreateNewFile;
    [self.view insertSubview:textView atIndex:0];
    _textView = textView;
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    toolbar.hidden = YES;
    self.textView.inputAccessoryView = toolbar;
    
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace) target:nil action:nil];
    
    UIBarButtonItem *finishItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemDone) target:self action:@selector(hideKeyboard)];
    
    toolbar.items = @[item1, finishItem];
}

- (void)hideKeyboard{
    
    [self.view endEditing:YES];
}

- (void)buildTabBar{
    
    [self tabBar];
    
    UIButton *editButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    editButton.frame = CGRectMake(0, 0, 49, 49);
    [editButton setTitle:@"编辑" forState:(UIControlStateNormal)];
    [self.tabBar addSubview:editButton];
    _editButton = editButton;
    
    [editButton addTarget:self action:@selector(editButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *saveButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    saveButton.frame = CGRectMake(self.tabBar.frame.size.width - 49, 0, 49, 49);
    [saveButton setTitle:@"保存" forState:(UIControlStateNormal)];
    [self.tabBar addSubview:saveButton];
    _saveButton = saveButton;
    
    [saveButton addTarget:self action:@selector(saveButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *previewButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    previewButton.frame = CGRectMake((self.tabBar.frame.size.width - 49) * 0.5, 0, 49, 49);
    [previewButton setTitle:@"预览" forState:(UIControlStateNormal)];
    previewButton.hidden = YES;
    [self.tabBar addSubview:previewButton];
    _previewButton = previewButton;
    
    [previewButton addTarget:self action:@selector(previewButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)editButtonClick:(UIButton *)button{
    
    if ([button.currentTitle isEqualToString:@"编辑"]) {
        
        [self enterEditingMode];
        
    } else {
        
        [self exitEditingMode];
    }
}

- (void)saveButtonClick:(UIButton *)button{
    
    if (!self.folderItem.filePath || !self.navTitle) { return; }
    
    button.userInteractionEnabled = NO;
    
    NSString *filePath = [self.folderItem.filePath stringByAppendingPathComponent:self.navTitle];
    
    NSError *error;
    
    BOOL success = [self.textView.text writeToFile:filePath atomically:YES encoding:self.encoding error:&error];
    
    if (error || !success) {
        
        [self showStatusWithMessage:@"保存失败！"];
        
    } else {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerDidAddFileNotification object:nil userInfo:filePath ? @{JKFileExplorerFileOperateDestinationFilePathsKey : filePath} : nil];
        
        [self showStatusWithMessage:@"保存成功！"];
        
        if (!self.filePath) {
            
            self.filePath = filePath;
            
            self.shareItem.enabled = YES;
        }
    }
    
    [self exitEditingMode];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.saveButton.userInteractionEnabled = YES;
    });
}

- (void)previewButtonClick:(UIButton *)button{
    
    if (!self.filePath) { return; }
    
    NSURL *URL = [NSURL fileURLWithPath:self.filePath];
    
    [JKFileExplorerPreviewController showWithPreviewItemList:@[URL] index:0 viewController:self];
}

- (void)enterEditingMode{
    
    [self.editButton setTitle:@"取消" forState:(UIControlStateNormal)];
    
    self.textView.editable = YES;
    
    self.textView.inputAccessoryView.hidden = NO;
    
    [self.textView becomeFirstResponder];
}

- (void)exitEditingMode{
    
    [self.editButton setTitle:@"编辑" forState:(UIControlStateNormal)];
    
    self.textView.editable = NO;
    
    self.textView.inputAccessoryView.hidden = YES;
}

- (void)loadData{
    
    NSError *error = nil;
    
    NSStringEncoding encoding;
    
    NSString *text = [NSString stringWithContentsOfFile:self.filePath usedEncoding:&encoding error:&error];
    
    if (error) {
        
        // GBK
        unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        
        error = nil;
        
        text = [NSString stringWithContentsOfFile:self.filePath encoding:encode error:&error];
        
        if (error) {
            
            self.editButton.hidden = YES;
            self.saveButton.hidden = YES;
            
            self.previewButton.hidden = NO;
            
            NSString *tip = error.localizedDescription ? error.localizedDescription : @"文件打开失败";
            
            self.tipLabel.text = [tip stringByAppendingString:@"\n点击下方预览按钮使用系统预览"];
            self.tipLabel.hidden = NO;
            
        } else {
            
            self.textView.text = text;
            
            self.encoding = encode;
        }
        
    } else {
     
        self.textView.text = text;
        
        self.encoding = encoding;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end
